﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Threading;
using ModelLayer;
using AssessmentTool.PresentationLogic.EventArguments;
using System.IO;
using AssessmentTool.PresentationLogic.Controllers.UIInterface;

namespace AssessmentTool.PresentationLogic.Controllers
{
    public class ApplicationController:AbstractController<IMainPage>
    {
         
        public static Object busyObject = new Object();
        public ApplicationController(IMainPage element)
            : base(element)
        {
            ed.subscrive("STOPBUSY", element.stopBusy);
            ed.subscrive("BUSY", element.startBusy);
            ed.subscrive("SHOWMESSAGE", showMessage);
            ed.subscrive("LOGOUT", logout);
            ed.subscrive("SAVELOCALPDF", savePdf);
            
        }
        public void savePdf(EventArgs e)
        {
            FileDownloadedEventArgs evento = (FileDownloadedEventArgs)e;
            SaveFileDialog d = new SaveFileDialog();
            d.Filter = "PDF file format|*.pdf";
            if (d.ShowDialog() == true)
            {

                Stream s = d.OpenFile();
                MemoryStream ms = new MemoryStream(evento.file);
                ms.WriteTo(s);
                s.Flush();
                s.Close();
                ms.Close();

            }
        }
    

       
        public void setBusy(EventArgs e)
        {

                element.IsEnabled = false;
                element.startBusy(e);
        }

        public void stopBusy(EventArgs e)
        {

                element.IsEnabled = true;
                element.stopBusy(e);
        }

      


        public void logout(EventArgs e)
        {
            
            Session.getInstance().removeValue("USER");
            ed.dispatch("CLEARCOMPETENZE", null);
            ed.dispatch("STOPBUSY", null);
        }

        public void showMessage(EventArgs ev)
        {
            ShowMessageEventArgs e = (ShowMessageEventArgs)ev;
            ModalWindow mw = new ModalWindow();
            if (e.Error)
            {
                mw.Show("Error", e.Testo, ModalType.CONTINUE);
                if (e.Critico)
                {
                    ed.dispatch("LOGOUT",null);
                }
            }
            else
            {
                mw.Show("Informazione",e.Testo, ModalType.CONTINUE);
            }
        }


    }
}
